//
//  LSZNewSearchVC.m
//  JKFuYinProject
//
//  Created by 九酷 on 2017/12/14.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LSZNewSearchVC.h"
#import "UITableView+SDAutoTableViewCellHeight.h"
#import "NetworkTool+LCAVPlay.h"

@interface LSZNewSearchVC ()

@end

@implementation LSZNewSearchVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setSearchUI];
    [self.tableViewResults registerClass:[LSZAudioRearchTableViewCell class] forCellReuseIdentifier:@"LSZAudioRearchTableViewCell"];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //历史记录
     if (tableView == self.tableViewHistorical) {
         if(self.tableViewHistorical.hidden == YES){
             return 0;
         }
         return self.historyMutArray.count;
     }else{
         if (self.tableViewResults.hidden == YES) {
             return 0;
         }
         return self.mutArrayContent.count;
     }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableViewHistorical) {
        if (ScreenWidth == 320) {
            //5
            return 45;
        }else if(ScreenWidth == 375){
            // 6 7
            return 50;
        }
        else{
            //plus
            return 58;
        }
    }
    else if(tableView == self.tableViewResults){
        if ([self.type isEqualToString:@"-1"] || [self.type isEqualToString:@"0"]) {
            return 125;
        }
        if([self.type isEqualToString:@"1"]){
            if(ScreenWidth >=375){
                return 70;
            }else{
                return 60;
            }
        }
        if(ScreenWidth >=375){
            return 118 ;
        }else{
            return 112;
        }
    }
    else{
        return 0;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == self.tableViewHistorical) {
        if(ScreenWidth >=375){
            return  34;
        }else{
            return  24;
        }
    }else{
        return 0.001;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UITableViewHeaderFooterView * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerCell"];
    if (!cell) {
        cell = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"headerCell"];
    }
    if (tableView == self.tableViewHistorical) {
        cell.textLabel.text = @"历史记录";
        cell.textLabel.textColor = titleColorLSZ;
        [LSZSpecialPackaging setLabelAdaptiveSize:cell.textLabel font:10.5];
    }else{
        cell.textLabel.hidden = YES;
    }
     return cell;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //历史记录
    if (tableView == self.tableViewHistorical) {
        LSZSearchHistoricalTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZSearchHistoricalTableViewCell" forIndexPath:indexPath];
        if (indexPath.row >= self.historyMutArray.count) {
            return cell;
        }
        Person *person = self.historyMutArray[indexPath.row];
        cell.labelTitle.text = [NSString stringWithFormat:@"%@",person.name];
        cell.butDeteting.tag = indexPath.row+1;
        cell.imageViewDeteting.tag =  indexPath.row+1;
        [cell.butDeteting addTarget:self action:@selector(clickButDetatle:) forControlEvents:UIControlEventTouchUpInside];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    if ([self.type isEqualToString:@"-1"] ||[self.type isEqualToString:@"0"]/**圣经旧约新约*/) {
        //搜索结果
        LCShengJingSearchResultsCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ShengJingSearchResultsCell" forIndexPath:indexPath];
        if (indexPath.row >= self.mutArrayContent.count) {
            return cell;
        }
        LSZSearchKeyContentMg *mg = nil;
        mg = self.mutArrayContent[indexPath.row];
        cell.contentMg = mg;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if ([self.type isEqualToString:@"1"]){
        //音频
        LSZAudioRearchTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZAudioRearchTableViewCell" forIndexPath:indexPath];
        if (indexPath.row >= self.mutArrayContent.count) {
            return cell;
        }
        LSZSearchKeyContentMg * mg = nil;
        mg = self.mutArrayContent[indexPath.row];
        cell.labelNumber.text = [NSString stringWithFormat:@"%zd",indexPath.row+1];
        cell.lableTitle.text = NSStr(mg.title);
        cell.labelIntroduce.text = NSStr(mg.album);
        cell.labelClick.text = NSStr(mg.browseNum);
        if (_LCPlayer.selectedIndex == indexPath.row && [cell.lableTitle.text isEqualToString:_LCPlayer.playingSong.title] && [mg.album isEqualToString:_LCPlayer.playingSong.album]) {
            [cell didSelectRowCellWithIsSystemRed:YES];
        }else{
            [cell didSelectRowCellWithIsSystemRed:NO];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    //搜索结果 视频和文章
    LSZSearchResultsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZSearchResultsTableViewCell" forIndexPath:indexPath];
    if (indexPath.row >= self.mutArrayContent.count) {
        return cell;
    }
    LSZSearchKeyContentMg * mg = nil;
     mg = self.mutArrayContent[indexPath.row];
     cell.contentMg = mg;
    if ([self.type isEqualToString:@"2"]) {
        cell.butSmall.hidden = NO;
        cell.labelTime.text = [NSString stringWithFormat:@"%@次",mg.browseNum];
    }else{
        cell.butSmall.hidden = YES;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark -  dianji  -
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableViewResults) {
        LSZSearchKeyContentMg * mg = nil;
        mg = self.mutArrayContent[indexPath.row];
        if ([self.type isEqualToString:@"-1"] || [self.type isEqualToString:@"0"]) {
            NSString * tempStr = mg.title;
            [[TheHomeManager shareTheHomeManager] localShengJingSongMessage:[_TheHomeM getSongParentIdWithTitle:tempStr]];
            LCPlaylist *playlistTest = _PlaylistMgr.allPlaylists.firstObject;
            _LCPlayer.songs = playlistTest.allSongs;
            if (_LCPlayer.songs != nil) {
                [_LCPlayer playAtIndex:[[tempStr substringWithinBoundsLeft:@"第" right:@"章"] integerValue]
                 -1 isSelectPlay:YES];
            }
            ///  跳转
            LCShengJingTextViewController *shengjMessageVC = [[LCShengJingTextViewController alloc] init];
            [self.navigationController pushViewController:shengjMessageVC animated:YES];

        }
       else  if ([self.type isEqualToString:@"1"]) {
            //音频
#pragma mark - 如果当前播放的就是点击的直接返回
           if ([_LCPlayer.playingSong.id isEqualToString:[NSString stringWithFormat:@"%@",mg.id_id]]) {
               return;
           }
           NSMutableArray * arrayMut = [[NSMutableArray alloc]init];
           for (LSZSearchKeyContentMg * audioMg in self.mutArrayContent) {
               NSDictionary *dict = [audioMg yy_modelToJSONObject];
               [arrayMut addObject:dict];
           }
           [LSZSpecialPackaging addPlaylistWithArrayData:arrayMut];
           LCPlaylist *playlistTest = _PlaylistMgr.allPlaylists.firstObject;
           _LCPlayer.songs = playlistTest.allSongs;
           [_LCPlayer playAtIndex:indexPath.row isSelectPlay:YES];//播放歌曲
           _LCPlayer.playingSong.id = mg.id_id;
           [LSZRequestData songClickOnTheDataUpdates:mg.id_id :^(BOOL isOk, NSString * str, NSDictionary * dic) {
               if (isOk == YES) {
                   //点击数更新OK
                   mg.browseNum = [NSString stringWithFormat:@"%d",[mg.browseNum intValue]+1];
                   [UIView performWithoutAnimation:^{
                       [self.tableViewResults reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                   }];
               }
           }];
           [self.tableViewResults reloadData];
           return;
        }
       else  if([self.type isEqualToString:@"2"]){
           //视频
           [SVProgressHUD showErrorWithStatus:@"点击没有反应,请提建议给我们!"];
           [SVProgressHUD dismissWithDelay:1];
//            [LSZSpecialPackaging increaseTheNumberOfViews:mg.id_id :^(BOOL isok) {
//                LSZSearchKeyContentMg * mg = nil;
//                mg = self.mutArrayContent[indexPath.row];
//                mg.browseNum = [NSString stringWithFormat:@"%zd",[mg.browseNum integerValue]+1];
//            }];
//
//            LCVideoHomeListAboutModel *listAboutModel = [LCVideoHomeListAboutModel new];
//            listAboutModel.id = mg.id_id;
//            listAboutModel.name = mg.title;
//            listAboutModel.pic = mg.imageUrl;
//            listAboutModel.author = mg.singerName;
//            listAboutModel.type = mg.type;
//            LTAdvancedManagerDemo *advancedManagerDemo = [[LTAdvancedManagerDemo alloc] init];
//            advancedManagerDemo.listAboutModel = listAboutModel;
//            [self.navigationController pushViewController:advancedManagerDemo animated:YES];
//            NSArray * arrayGetData = [[NSArray alloc] initWithContentsOfFile:[LSZSpecialPackaging recordTheBrowsingHistoryVideo]];
//            for (NSDictionary * dic in arrayGetData) {
//                NSString * name = NSStr(dic[@"id_id"]);
//                if ([name isEqualToString:mg.id_id]) {
//                    return;
//                }
//            }
//            //还没有添加过
//            NSMutableArray * mutArrayAdd = [[NSMutableArray alloc]initWithArray:arrayGetData];
//            NSMutableDictionary * mutDic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:mg.title,@"title",mg.imageUrl,@"imageViewUrl",mg.singerName,@"name",mg.id_id,@"id_id",nil];
//            [mutArrayAdd addObject:mutDic];
//            [mutArrayAdd writeToFile:[LSZSpecialPackaging recordTheBrowsingHistoryVideo] atomically:YES];

        }
       else if([self.type isEqualToString:@"3"]){
            //文章"
        [LSZSpecialPackaging increaseTheNumberOfViews:mg.id_id :^(BOOL isok) {
            mg.browseNum = [NSString stringWithFormat:@"%zd",[mg.browseNum integerValue]+1];
        }];
        LCWenHTMLViewController * VC = [[LCWenHTMLViewController alloc]init];
        VC.link = mg.remoteUrl;
//      VC.searchKeyContentMg = mg;
        VC.link = [NSString stringWithFormat:@"%@",mg.remoteUrl];
        NSDictionary *dict = [mg yy_modelToJSONObject];
        BeautifulEssayModel *model = [BeautifulEssayModel yy_modelWithJSON:dict];
        NSArray *urlArr = [mg.remoteUrl componentsSeparatedByString:@"/"];
        model.type = urlArr[urlArr.count-1];
        if ([model.type isEqualToString:@"2"] && _LCPlayer.kstatus == LCMusicPlayerStatusPlaying) {
           VC.PlayAudio = 1;
        }
        VC.model =model;
        [self.navigationController pushViewController:VC animated:YES];
     }
        //捐赠 5，电商
        if([self.type isEqualToString:@"4"]||[mg.type isEqualToString:@"5"]){
            if ([[_UserM usercode] isEqualToString:@""]) {
                [self goToLogin];
            }else{
                if([mg.type isEqualToString:@"4"]){
                    LCBeautifulEssayController *controller = [[LCBeautifulEssayController alloc] init];
                    controller.link = [NSString stringWithFormat:@"http://fuyin.app.inping.com/user/donation_rmb?usercode=%@",[_UserM usercode]];
                    [self.navigationController pushViewController:controller animated:YES];
                }else{
                    NSLog(@"电商");
                }
            }
         }
    }else{
        Person *person = self.historyMutArray[indexPath.row];
        self.countPage = 1;
        self.textFieldSearch.text = [NSString stringWithFormat:@"%@",person.name];
        self.searchString = [NSString stringWithFormat:@"%@",person.name];
         [self initWithDataCountStr:[NSString stringWithFormat:@"%@",person.name] :self.type :self.countPage];
        [self initesignFirstResponder];
    }
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return YES;
}
-(void)goToLogin
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"AccLogin" bundle:nil];
    UIViewController *controller = [sb instantiateInitialViewController];
    [self.navigationController pushViewController:controller animated:YES];
}
-(void)setSearchUI
{
    [self.navigationController.navigationItem setHidesBackButton:YES];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationController.navigationBar.backItem setHidesBackButton:YES];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"home_nav_button_back"] style:UIBarButtonItemStyleDone target:self action:@selector(back)];

    UIButton * butCancel = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    [butCancel setTitle:@"搜索" forState:UIControlStateNormal];
    [butCancel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [butCancel addTarget:self action:@selector(clickCancelBut) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:butCancel];

    self.view.backgroundColor = RGBColor(236, 236, 236);

    UIView * viewSearch = [[UIView alloc]initWithFrame:CGRectMake( 50, NAVIGATION_BAR_HEIGHT-37, ScreenWidth-80-30, 35)];
    viewSearch.backgroundColor = [UIColor whiteColor];
    [viewSearch.layer setMasksToBounds:YES];
    [viewSearch.layer setCornerRadius:5];
    viewSearch.userInteractionEnabled = YES;
    self.navigationItem.titleView = viewSearch;

    UIImageView * imageViewSearch = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 18, 18)];
    imageViewSearch.image = [UIImage imageNamed:@"灰色搜索"];
    [viewSearch addSubview:imageViewSearch];

    UITextField * textFieldSearch = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imageViewSearch.frame)+5, 5,viewSearch.frame.size.width-CGRectGetMaxX(imageViewSearch.frame)-13,30)];
    self.textFieldSearch = textFieldSearch;
    textFieldSearch.backgroundColor = [UIColor whiteColor];
    textFieldSearch.delegate = self;
    textFieldSearch.tintColor = [UIColor redColor];
    textFieldSearch.placeholder = @"搜索圣经,赞美诗...";
    textFieldSearch.textColor = titleColorLSZ;
    textFieldSearch.clearButtonMode = UITextFieldViewModeAlways;
    [viewSearch addSubview:textFieldSearch];
}
//点击return 按钮 去掉
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self clickCancelBut];
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
 {
    NSString * str = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if(str.length == 0 ){
        [self PopularAndHistoricalRecordsAreNOHidden];
     }else{
         if (self.collectionView.hidden == YES&&self.tableViewHistorical.hidden == YES ) {
             return YES;
         }else{
             [self PopularAndHistoricalRecordsAreHidden];
         }
    }
     return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    [self PopularAndHistoricalRecordsAreNOHidden];
    if (self.viewTop.hidden == NO&&self.tableViewResults.hidden== NO) {
        [self SearchResultsHidden];
    }
    return YES;
}
#pragma mark - 键盘
-(void)initesignFirstResponder
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}
#pragma mark - 搜索结果隐藏
-(void)SearchResultsHidden
{
    self.viewTop.hidden = YES;
    self.tableViewResults.hidden = YES;
}
#pragma mark - 热门和历史记录隐藏
-(void)PopularAndHistoricalRecordsAreHidden
{
    self.collectionView.hidden = YES;
    self.tableViewHistorical.hidden = YES;
}
-(void)PopularAndHistoricalRecordsAreNOHidden
{
    self.collectionView.hidden = NO;
    self.tableViewHistorical.hidden = NO;
    [self.tableViewHistorical reloadData];
}
#pragma mark - 搜索按钮的点击事件
-(void)clickCancelBut
{
    if (self.textFieldSearch.text.length > 0) {
        self.countPage = 1;
        [self searchCount:self.textFieldSearch.text :self.type :self.countPage];
        [self initesignFirstResponder];
    }else{
        [SVProgressHUD showErrorWithStatus:@"请输入您要搜索的关键词!"];
        [SVProgressHUD dismissWithDelay:1];
    }
}
#pragma mark - 点击的删除的那个
-(void)clickButDetatle:(UIButton *)but
{
    Person *person = self.historyMutArray[but.tag-1];
    [[DataBase sharedDataBase] deletePerson: person];
    self.historyMutArray = [[DataBase sharedDataBase] getAllPerson];
    self.historyMutArray = (NSMutableArray *)[[self.historyMutArray reverseObjectEnumerator] allObjects];
    [self.tableViewHistorical reloadData];
}
#pragma mark  - 选择的是那个
-(void)clickButSeare:(UIButton *)but {
    [self initesignFirstResponder];
     if (self.clickChoose == but.tag) {
        return;
    }
    self.clickChoose = but.tag;
    if(but.tag == 0){
        self.type = @"1";//1，音频
    }else if (but.tag == 1){
        self.type = @"3";//3，文章
    }else if (but.tag == 2){
        self.type = @"2";//2，视频
    }else if (but.tag == 3){
      self.type = @"-1";//-1，圣经旧约
    }else   {
       self.type = @"0";//0，圣经新约
    }
//    self.type = [NSString stringWithFormat:@"%zd",but.tag-1];
    self.countPage = 1;
    [self initWithDataCountStr:self.textFieldSearch.text  :self.type :self.countPage];
     CGRect rect = self.labelRed.frame;
    rect.origin.x = (but.tag)%5*60;
    self.labelRed.frame = rect;
    [self.tableViewResults reloadData];
}
#pragma mark - 导航的返回键
-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
@end
